package com.tianhui.consignortwofei.mvp.ui.fragment;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.fragment.app.FragmentActivity;

import com.fgs.common.CommonResponse;
import com.fgs.common.other.CommonEvent;
import com.fgs.common.permission.OnPermissionCheckResult;
import com.fgs.common.permission.PermissionHelper;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.constant.KeyValue;
import com.tianhui.consignortwofei.constant.OrderType;
import com.tianhui.consignortwofei.manager.SharedPreferenceManager;
import com.tianhui.consignortwofei.mvp.contract.OrderListContract;
import com.tianhui.consignortwofei.mvp.model.OrderModel;
import com.tianhui.consignortwofei.mvp.model.enty.OrderCondition;
import com.tianhui.consignortwofei.mvp.model.enty.OrderInfo;
import com.tianhui.consignortwofei.mvp.model.enty.OrderOperateInfo;
import com.tianhui.consignortwofei.mvp.presenter.OrderListPresenter;
import com.tianhui.consignortwofei.mvp.ui.activity.LiuLanLogActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.OrderDetailActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.SaleCarFreightActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.TongHuaLogActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.deliverGoods.edit.EditDeliveryGoodsStepOneActivity;
import com.tianhui.consignortwofei.mvp.ui.adapter.WeiFreightPayListAdapter;
import com.tianhui.consignortwofei.other.EventWhat;
import com.tianhui.consignortwofei.pattern.orderOprate.IOrderOperate;
import com.tianhui.consignortwofei.pattern.orderOprate.impl.FreightOperate;
import com.tianhui.consignortwofei.pattern.orderStatus.status.IOrderStatus;
import com.tianhui.consignortwofei.widget.QRCodeDialog;
import com.xuexiang.xaop.annotation.IOThread;
import com.xuexiang.xaop.enums.ThreadType;
import com.xuexiang.xqrcode.XQRCode;
import com.xuexiang.xutil.display.ImageUtils;
import com.xuexiang.xutil.security.Base64Utils;

import org.yczbj.ycrefreshviewlib.adapter.RecyclerArrayAdapter;
import org.yczbj.ycrefreshviewlib.inter.OnItemChildClickListener;
import org.yczbj.ycrefreshviewlib.inter.OnItemClickListener;

import io.reactivex.Observable;

/**
 * @author fgs
 * @date 2020/8/27
 * @description
 **/
public class WeiFreightPayListFragment extends SearchFragment<OrderListContract.View, OrderListContract.Presenter> implements OrderListContract.View {

    private boolean isNeedLazyLoad = true;
    private IOrderStatus mIOrderStatus;
    private String mSearchKey;
    private int setWhichShow;

    public WeiFreightPayListFragment() {
        // Required empty public constructor
    }

    @Override
    protected void changeSearchKey(String searchKey) {
        mSearchKey = searchKey;
    }

    @Override
    public boolean isNeedLazyLoad() {
        return this.isNeedLazyLoad;
    }

    public static WeiFreightPayListFragment newInstance(IOrderStatus iOrderStatus) {
        WeiFreightPayListFragment orderListFragment = new WeiFreightPayListFragment();
        orderListFragment.setOrderStatus(iOrderStatus);
        return orderListFragment;
    }

    private WeiFreightPayListFragment setOrderStatus(IOrderStatus iOrderStatus) {
        mIOrderStatus = iOrderStatus;
        return this;
    }

    public WeiFreightPayListFragment setIsNeedLazyLoad(boolean isNeedLazyLoad) {
        this.isNeedLazyLoad = isNeedLazyLoad;
        return this;
    }

    public WeiFreightPayListFragment setWhichShow(int num) {
        this.setWhichShow = num;
        return this;
    }

    public WeiFreightPayListFragment setSearchKey(String searchKey) {
        mSearchKey = searchKey;
        return this;
    }


    @Override
    protected OrderListContract.View createView() {
        return this;
    }

    @Override
    protected OrderListContract.Presenter createPresenter() {
        return new OrderListPresenter(getContext());
    }


    @Override
    public RecyclerArrayAdapter createAdapter() {
        return new WeiFreightPayListAdapter(getContext(), mIOrderStatus,setWhichShow);
    }

    @Override
    protected void initListener() {

        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Object object = mAdapter.getAllData().get(position);
                if (object instanceof OrderInfo) {
                    OrderInfo orderInfo = (OrderInfo) object;
                    Bundle bundle = new Bundle();
                    bundle.putParcelable(KeyValue.KEY_ORDER_INFO, orderInfo);
                    bundle.putInt(KeyValue.KEY_TYPE, mIOrderStatus.getOrderStatusType());

                    //运费计算
                    yunfeiJIsuan(orderInfo);

//                    if (mIOrderStatus.getOrderStatusType() != OrderType.TYPE_PAYMENT) {
//                        openActivity(OrderDetailActivity.class, bundle);
//                    }
                }

            }
        });

        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(View view, int position) {
                Object object = mAdapter.getAllData().get(position);
                OrderInfo orderInfo = null;
                if (object instanceof OrderInfo) {
                    orderInfo = (OrderInfo) object;
                }
                switch (view.getId()) {
//                    case R.id.tv_shenhe:
                    case R.id.item_order_list_submitTextView:

                        if (orderInfo != null) {
                            if (mIOrderStatus.getOrderStatusType() == OrderType.TYPE_PAYMENT) {
                                //申请付款

                               Bundle bundle = new Bundle();
                               bundle.putParcelable(KeyValue.KEY_ORDER_INFO, orderInfo);
                               bundle.putInt(KeyValue.KEY_TYPE, mIOrderStatus.getOrderStatusType());
                               openActivity(OrderDetailActivity.class, bundle);

                            }else {
                                //运费计算
                                yunfeiJIsuan(orderInfo);
//                                OrderOperateInfo  orderOperateInfo = new OrderOperateInfo();
//                                orderOperateInfo.operate = "运费计算";
//                                orderOperateInfo.iOrderOperate = new FreightOperate();
//                                orderOperateInfo.orderInfo = orderInfo;
//                                orderOperateInfo.type=0;
//                                orderOperateInfo.isEnable=true;
//                                IOrderOperate iOrderOperate = orderOperateInfo.iOrderOperate;
//                                iOrderOperate.orderOperate(getActivity(), orderOperateInfo);


                            }
                        }

//                        if (orderInfo != null) {
//                            Bundle bundle = new Bundle();
//                            bundle.putParcelable(KeyValue.KEY_ORDER_INFO, orderInfo);
//                            bundle.putInt(KeyValue.KEY_TYPE, mIOrderStatus.getOrderStatusType());
//                            openActivity(OrderDetailActivity.class, bundle);
//                        }


                        break;
                    case R.id.item_order_list_shareOrderCodeTextView:
                        if (orderInfo != null) {
                            showShareCode(orderInfo);
                        }
                        break;
                    case R.id.item_order_list_editOrderTextView:
                        if (orderInfo != null) {
                            Bundle bundle = new Bundle();
                            bundle.putString(KeyValue.KEY_ID, orderInfo.id);
                            openActivity(EditDeliveryGoodsStepOneActivity.class, bundle);
                        }
                        break;
                    case R.id.tv_tonghua:
                        if (orderInfo != null) {
                            Bundle bundle = new Bundle();
                            bundle.putString("sourcenum", orderInfo.billno);
                            openActivity(TongHuaLogActivity.class, bundle);
                        }
//                        Toast.makeText(getContext(), "通话记录", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.tv_liulan:
                        if (orderInfo != null) {
                            Bundle bundle = new Bundle();
                            bundle.putString("sourcenum", orderInfo.billno);
                            openActivity(LiuLanLogActivity.class, bundle);
                        }
//                        Toast.makeText(getContext(), "浏览记录", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });

    }



    private void showShareCode(OrderInfo orderInfo) {
        new PermissionHelper().checkPermissions((FragmentActivity) getContext(), new OnPermissionCheckResult() {
            @Override
            public void grantedResult() {

                if (!TextUtils.isEmpty(orderInfo.billno)) {
                    String base64BillNo = Base64Utils.encode(orderInfo.billno);
                    Bitmap bitmap = createQRCodeWithLogo(base64BillNo, ImageUtils.getBitmap(R.mipmap.icon_app));
                    new QRCodeDialog(getContext(), bitmap).show();
                } else {
                    showToast("获取订单信息失败");
                }

            }

            @Override
            public void shouldShowRequestPermissionRationale() {

            }

            @Override
            public void grantedForbidResult() {

            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    /**
     * 生成简单的带logo的二维码
     *
     * @param content
     * @param logo
     */
    @IOThread(ThreadType.Single)
    private Bitmap createQRCodeWithLogo(String content, Bitmap logo) {
        Bitmap bitmap = XQRCode.createQRCodeWithLogo(content, 400, 400, logo);
        return bitmap;
    }

    @Override
    public void requestDataList(int page, boolean isDialog) {
        if (mIOrderStatus != null) {
            OrderCondition orderCondition = new OrderCondition();
            orderCondition.page = page;
            orderCondition.searchKey = mSearchKey;
            getPresenter().requestOrderList(mIOrderStatus.getOrderListObservable(orderCondition), isDialog);
        }
    }

    @Override
    public void initData() {

        if (mIOrderStatus != null)
            setSearchKeyHint(mIOrderStatus.getSearchHint());
    }

    @Override
    protected void requestSearch(String searchKey) {
        mSearchKey = searchKey;
        refreshData(true);
    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (EventWhat.valueOf(event.getWhat())) {
            case EVENT_REFRESH_ORDER_LIST:
                if (isHasLoadData())
                    refreshData(false);
                break;
        }
    }



    private void yunfeiJIsuan(OrderInfo mOrderInfo) {
        if (mOrderInfo != null && mIOrderStatus != null) {
            OrderCondition orderCondition = new OrderCondition();
            orderCondition.dispatchNo = mOrderInfo.dispatchno;
            orderCondition.billNo = mOrderInfo.billno;
            orderCondition.orderId = mOrderInfo.id;
            requestOrderDetail(mIOrderStatus.getOrderDetailObservable(orderCondition), true, mIOrderStatus.getOrderStatusType());
        }
    }


    public void requestOrderDetail(Observable observable, boolean isDialog, int orderType) {
        OrderModel  mModel = new OrderModel();
            mModel.orderDetailModel(getActivity(), observable, true, bindLifecycle(), new ObserverResponseListener<CommonResponse<OrderInfo>>() {
                @Override
                public void onNext(CommonResponse<OrderInfo> commonResponse) {
                    if (commonResponse.getCode() == 20000) {
                        OrderInfo info = commonResponse.getData();
                        if (null != info && mIOrderStatus != null) {
//                            getView().showOrderDetailList(mIOrderStatus.getOrderDetailList(info));

                            int rolePosition = SharedPreferenceManager.getInstance().getRolePosition();
                            if (2 == rolePosition) {
                                //2 销售，3物流
                                Intent intent = new Intent(getActivity(), SaleCarFreightActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putParcelable(KeyValue.KEY_ORDER_INFO,info);
                                intent.putExtras(bundle);
                                getActivity().startActivity(intent);
                            } else {
                                OrderOperateInfo  orderOperateInfo = new OrderOperateInfo();
                                orderOperateInfo.operate = "运费计算";
                                orderOperateInfo.iOrderOperate = new FreightOperate();
                                orderOperateInfo.orderInfo = info;
                                orderOperateInfo.type=0;
                                orderOperateInfo.isEnable=true;
                                IOrderOperate iOrderOperate = orderOperateInfo.iOrderOperate;
                                iOrderOperate.orderOperate(getActivity(), orderOperateInfo);
                            }

                        }
                    } else {
                        setMsg(commonResponse.getMsg());
                    }
                }

                @Override
                public void onError(ExceptionHandle.ResponseThrowable e) {
                    setMsg(e.message);
                }
            });



    }

}
